package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * @author DL5O
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登陆
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        /**
         * 1. 将页面提交的密码password进行MD5进行加密
         * 2. 根据页面提交的用户名username查询数据库
         * 3. 如果没查询到则返回登陆失败
         * 4. 密码比对，如果不一致则返回登陆失败信息
         * 5. 查看员工状态，如果为已禁用状态，则返回员工已禁用
         * 6. 登陆成功，将员工id存入Session并返回登陆成功结果(把登陆后的员工信息返回给前端)
         */
        String password = employee.getPassword();
        //1.使用DigestUtils 把明文密码转换为密文密码
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(qw);

        //3.如果没查询到则返回登陆失败
        if (emp == null) {
            return R.error("用户不存在！请重新登陆");
        }

        //4.密码比对，如果不一致则返回登陆失败信息
        if (!emp.getPassword().equals(password)) {
            return R.error("用户密码错误！请重新登陆");
        }

        //5.查看员工状态，如果为已禁用状态，则返回员工已禁用
        if (emp.getStatus() == 0) {
            return R.error("员工已禁用!");
        }

        //6.登陆成功，将员工id存入Session并返回登陆成功结果
        HttpSession session = request.getSession();
        session.setAttribute("employee", emp.getId());

        return R.success(emp);
    }


    /**
     * 员工退出
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        /**
         * 1. 请求Session中的用户id
         * 2. 返回结果
         */
        HttpSession session = request.getSession();
        session.removeAttribute("employee");
        return R.success("删除成功！");
    }

    /**
     * 新增员工
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    @CacheEvict(value = "employeeCache",allEntries = true)
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        long id = Thread.currentThread().getId();
        log.info("线程id:{}", id);

        log.info("新增员工,员工信息:{}", employee.toString());
        //1.设置初始密码为123456
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());

        employee.setPassword(password);
        //2.设置员工相关信息
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);*/

        //3.调用service方法，把员工信息保存到数据库中
        boolean save = employeeService.save(employee);

        return save ? R.success("保存成功") : R.error("保存失败");
    }

    /**
     * 员工信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = "employeeCache",
            key = "'employeePage_' + #page + '_' + #pageSize",
            unless = "#result.getCode() == 0")
    public R<Page<Employee>> getPage(int page, int pageSize, @RequestParam(required = false) String name) {

        //1.创建Page对象，该对象中封装了records，total等信息，这些信息也是前端所需要的
        Page<Employee> iPage = new Page(page, pageSize);
        log.info("name={}", name);

        //2.判断是否接受到name，如果有，就进行带条件的分页查询
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        qw.orderByDesc(Employee::getUpdateTime);//按照创建时间进行降序排序

        //3.调用service层进行分页查询
        iPage = employeeService.page(iPage, qw);
        //log.info(iPage.toString());
        return R.success(iPage);
    }

    /**
     * 公共的修改方法
     * @param employee
     * @return
     */
    @CacheEvict(value = "employeeCache",allEntries = true)
    @PutMapping
    public R<String> updateStatus(HttpServletRequest request, @RequestBody Employee employee) {
        long id = Thread.currentThread().getId();
        //log.info("线程id:{}", id);

        //log.info(employee.toString());
        //1.从session域总获取当前员工（管理员）的id
        Long updateUser = (Long) request.getSession().getAttribute("employee");
        //log.info("修改人id：{}", updateUser);

        //2.把当前修改人,修改时间设置到employee中
        employee.setUpdateUser(updateUser);
        employee.setUpdateTime(LocalDateTime.now());

        //4.判断是否修改成功
        boolean flag = employeeService.updateById(employee);
        return flag ? R.success("员工信息修改成功") : R.error("员工信息修改失败");
    }

    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        log.info("当前员工id:" + id);
        Employee employee = employeeService.getById(id);
        log.info("当前员工信息:" + employee);
        return employee!=null ? R.success(employee):R.error("未知错误");
    }
}
